import type { IMenu } from '../../pages/login/api/interface'
import type { ISearchResult } from '../../pages/menu/api/interface'
import type { IMenuCategory, IAppCategory, IFilterParams } from './types'
import { getIconForCategory } from './icons'

/**
 * 菜单筛选功能模块
 * 包含菜单搜索、分类筛选、应用分类生成等功能
 */

/**
 * 根据搜索关键词和分类筛选应用
 * @param apps 应用列表（保留参数以兼容现有代码）
 * @param searchKeyword 搜索关键词
 * @param selectedCategory 选中的分类ID，'all'表示全部
 * @param menuCategories 菜单分类数据
 * @returns 筛选后的应用列表
 */
export const filterApps = (
  apps: IMenu[],
  searchKeyword: string,
  selectedCategory: string = 'all',
  menuCategories: IMenuCategory[] = []
): IMenu[] => {
  let filteredApps: IMenu[] = []

  if (selectedCategory === 'all') {
    // 显示所有过滤后的应用
    filteredApps = menuCategories.flatMap(category => category.children)
  } else {
    // 显示特定分类的应用
    const selectedCategoryData = menuCategories.find(
      category => category.category.Id === selectedCategory
    )
    if (selectedCategoryData) {
      filteredApps = selectedCategoryData.children
    }
  }

  // 按搜索关键词过滤
  if (searchKeyword) {
    const keyword = searchKeyword.toLowerCase()
    filteredApps = filteredApps.filter(app =>
      app.Text.toLowerCase().includes(keyword) ||
      (app.Url && app.Url.toLowerCase().includes(keyword))
    )
  }

  return filteredApps
}

/**
 * 高级菜单筛选（使用参数对象）
 * @param params 筛选参数
 * @returns 筛选后的应用列表
 */
export const filterAppsAdvanced = (params: IFilterParams): IMenu[] => {
  const { searchKeyword = '', selectedCategory = 'all', menuCategories = [] } = params
  return filterApps([], searchKeyword, selectedCategory, menuCategories)
}

/**
 * 根据已添加的应用和菜单分类生成应用分类数据
 * @param addedApps 已添加的应用列表
 * @param menuCategories 菜单分类数据
 * @returns 应用分类数据
 */
export const generateAppCategories = (
  addedApps: ISearchResult[],
  menuCategories: IMenuCategory[]
): IAppCategory[] => {
  if (!addedApps.length || !menuCategories.length) {
    return []
  }

  const categories: IAppCategory[] = []

  // 遍历菜单分类
  menuCategories.forEach((categoryData, index) => {
    const category = categoryData.category

    // 找到该分类下的已添加应用
    const categoryApps = addedApps.filter(app => {
      // 在该分类的子菜单中查找
      return categoryData.children.some(
        (child: any) => child.Id === app.MenuId
      )
    })

    if (categoryApps.length > 0) {
      categories.push({
        id: category.Id,
        name: category.Text,
        icon: getIconForCategory(category.Text, index),
        apps: categoryApps
      })
    }
  })

  return categories
}

/**
 * 检查应用是否已添加
 * @param appId 应用ID
 * @param addedApps 已添加的应用列表
 * @returns 是否已添加
 */
export const isAppAdded = (appId: string, addedApps: ISearchResult[]): boolean => {
  return addedApps.some(app => app.MenuId === appId)
}

/**
 * 搜索处理函数（可扩展防抖功能）
 * @param keyword 搜索关键词
 * @param callback 搜索回调函数
 * @param debounceMs 防抖延迟时间（毫秒）
 */
export const handleSearch = (
  keyword: string,
  callback?: (keyword: string) => void,
  debounceMs?: number
) => {
  if (debounceMs && debounceMs > 0) {
    // 实现防抖逻辑
    const timeoutId = setTimeout(() => {
      if (callback) {
        callback(keyword)
      }
    }, debounceMs)

    // 返回清除函数
    return () => clearTimeout(timeoutId)
  } else {
    // 直接执行
    if (callback) {
      callback(keyword)
    }
  }
}

/**
 * 分类选择处理函数
 * @param categoryId 分类ID
 * @param callback 选择回调函数
 */
export const handleCategorySelect = (categoryId: string, callback?: (categoryId: string) => void) => {
  if (callback) {
    callback(categoryId)
  }
}

/**
 * 根据关键词在菜单中搜索（仅搜索ShowOnMenu为true的菜单）
 * @param menus 菜单列表
 * @param keyword 搜索关键词
 * @param searchFields 搜索字段
 * @returns 搜索结果
 */
export const searchInMenus = (
  menus: IMenu[],
  keyword: string,
  searchFields: (keyof IMenu)[] = ['Text', 'Url']
): IMenu[] => {
  // 首先过滤掉ShowOnMenu为false的菜单
  const visibleMenus = menus.filter(menu => menu.ShowOnMenu)

  if (!keyword) return visibleMenus

  const lowerKeyword = keyword.toLowerCase()

  return visibleMenus.filter(menu => {
    return searchFields.some(field => {
      const value = menu[field]
      return value && String(value).toLowerCase().includes(lowerKeyword)
    })
  })
}

/**
 * 按分类分组菜单（仅处理ShowOnMenu为true的菜单）
 * @param menus 菜单列表
 * @param menuCategories 菜单分类数据
 * @returns 分组后的菜单
 */
export const groupMenusByCategory = (
  menus: IMenu[],
  menuCategories: IMenuCategory[]
): Record<string, IMenu[]> => {
  const grouped: Record<string, IMenu[]> = {}

  // 首先过滤掉ShowOnMenu为false的菜单
  const visibleMenus = menus.filter(menu => menu.ShowOnMenu)

  menuCategories.forEach(category => {
    const categoryMenus = visibleMenus.filter(menu =>
      category.children.some(child => child.Id === menu.Id)
    )
    grouped[category.category.Id] = categoryMenus
  })

  return grouped
}

/**
 * 获取筛选统计信息
 * @param params 筛选参数
 * @returns 筛选统计信息
 */
export const getFilterStats = (params: IFilterParams) => {
  const { searchKeyword = '', selectedCategory = 'all', menuCategories = [] } = params
  const filteredApps = filterAppsAdvanced(params)

  return {
    totalCategories: menuCategories.length,
    totalApps: menuCategories.flatMap(cat => cat.children).length,
    filteredApps: filteredApps.length,
    hasSearch: !!searchKeyword,
    hasCategory: selectedCategory !== 'all',
    selectedCategory
  }
}
